<template>
  <div class="body">
    <div class="article-list">
      <el-card
        v-for="article in articleList"
        :key="article.id"
        class="article-card"
        shadow="always"
      >
        <h2 class="article-title">
          {{ article.title }}
        </h2>
        <div class="article-meta">
          <!-- 新增作者标签 -->
          <el-tag type="warning" size="small"
            >作者：{{ article.authorName }}</el-tag
          >
          <el-tag type="info" size="small"
            >分类：{{ article.categoryName }}</el-tag
          >
          <el-tag
            v-for="tag in article.tags.split(',')"
            :key="tag"
            type="success"
            size="small"
          >
            {{ tag }}
          </el-tag>
          <span class="time">{{ formatTime(article.created_at) }}</span>
        </div>
        <!-- 添加ref用于获取渲染后的DOM -->
        <vue-markdown
          ref="markdownRenderer"
          :source="truncateContent(article.content)"
          class="markdown-content"
        />
        <!-- 替换阅读量为点赞图标 -->
        <div class="bottom-clearfix">
          <div class="article-like" @click.stop="handleLike(article)">
            <i
              class="iconfont icon-icon like-icon"
              :class="{ liked: article.liked }"
            ></i>
            <span class="like-count">{{ article.like_count }}</span>
          </div>
          <el-button
            type="primary"
            size="small"
            @click="handleArticleClick(article)"
          >
            查看详情
          </el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getArticleList, getCategoryName, postLike, getUserInfo } from "@/api"; // 新增：导入点赞接口
import VueMarkdown from "vue-markdown";

export default {
  components: {
    VueMarkdown,
  },
  data() {
    return {
      articleList: [],
    };
  },
  async mounted() {
    try {
      const userId = this.$store.state.user?.id;
      const res = await getArticleList();

      // 关键修复：兼容不同数据结构（假设后端可能返回 res.data 是数组）
      const rawArticles = res.data.data || res.data; // 优先取 res.data.data，否则直接用 res.data
      if (!Array.isArray(rawArticles)) {
        throw new Error("文章列表数据格式错误");
      }

      const articlesWithData = [];
      for (const article of rawArticles) {
        // 改为遍历 rawArticles
        // 获取分类名称（假设 getCategoryName 返回 { data: { name } }）
        const categoryRes = await getCategoryName(article.category_id);
        const categoryName = categoryRes.data.data.name || "未分类";

        // 获取作者信息（假设文章有 user_id 字段）
        const userRes = await getUserInfo(article.user_id); // 调用获取用户接口

        const authorName = userRes.data.user.username || "未知用户"; // 假设接口返回 username

        // 处理点赞状态
        let liked = false;
        if (article.like_users_id) {
          const likeUserIds = article.like_users_id.split(",");
          liked = likeUserIds.some((id) => id == userId);
        }

        // 合并处理后的数据
        articlesWithData.push({
          ...article,
          categoryName,
          authorName, // 新增作者名称
          liked,
        });
      }

      // 所有异步操作完成后，再赋值给 articleList（触发界面渲染）
      this.articleList = articlesWithData;
      console.log(this.articleList);
    } catch (err) {
      console.error("加载文章列表失败：", err);
      this.$message.error("加载文章列表失败，请刷新重试");
    }
  },
  methods: {
    formatTime(time) {
      return new Date(time).toLocaleDateString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
      });
    },
    truncateContent(html) {
      const cleanedHtml = html.replace(/<\/?(?!code\b)[^>]+>/gi, "");
      const truncated = cleanedHtml.slice(0, 100);
      return cleanedHtml.length > 100 ? truncated + "..." : truncated;
    },
    // 新增：点赞处理方法
    async handleLike(article) {
      if (!this.$store.state.isLogin) {
        this.$message.warning("请先登录");
        return;
      }
      // 防止重复请求
      if (article.liked) return;
      try {
        const articleId = article.id;
        const userId = this.$store.state.user.id;
        const res = await postLike({ articleId: articleId, userId: userId }); // 调用后端点赞接口
        console.log(res);

        if (res.data.status === 0) {
          // 更新本地数据（同步点赞数和状态）
          article.like_count = res.data.data.like_count;
          article.liked = true;
          this.$message.success("点赞成功");
        } else {
          this.$message.error("点赞失败：" + res.data.message);
        }
      } catch (err) {
        console.log(err);

        this.$message.error("点赞请求异常");
      }
    },
    handleArticleClick(article) {
      console.log("点击了文章：", article);
      this.$router.push({
        path: `/article/detail/${article.id}`,
      });
    },
  },
};
</script>

<style scoped>
.article-card {
  pointer-events: auto; /* 确保可点击 */
  min-height: 100px; /* 避免高度为0无法点击 */
}
.article-meta .el-tag {
  margin-right: 5px;
}
.markdown-content {
  line-height: 1.8;
  font-size: 16px;
  margin-bottom: 15px;
}

/* 重置pre默认样式，避免与Prism冲突 */
.markdown-content pre {
  background: none;
  padding: 0;
  margin: 15px 0;
}

/* 覆盖Prism的代码块样式（可选） */
.markdown-content pre code {
  display: block;
  background: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  font-family: "Courier New", monospace;
  white-space: pre-wrap; /* 长代码自动换行 */
  overflow-x: auto; /* 超出部分滚动 */
}

/* 新增：点赞样式 */
.article-like {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #909399;
  cursor: pointer;
  transition: color 0.3s;
}

.article-like:hover {
  color: #1296db;
}

.like-icon {
  font-size: 18px;
}

.like-icon.liked {
  color: #1296db;
}

.like-count {
  font-size: 14px;
}
.bottom-clearfix {
  clear: both;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}
</style>
